using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Media;

namespace Trigits
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        private const int NUM_START_TRIOS = 2;
        private const int TIME_DIVIDE = 250;
        private float X_NEXT_TRIOMINOE_IN_SLATE = 250;
        private const int TRIO_MAX_VAL = 2;

        private GraphicsDeviceManager graphics;
        private SpriteBatch spriteBatch;
        private BasicEffect basicEffect;
        private SpriteFont triominoeFont;
        private Texture2D tableTexture;
        private GameTable table;
        private SlateContainer[] slateContainers;
        private Player[] players;
        
        private Player playingPlayer;
        private StackContainer stackContainer;
        private TriominoeContainer[] containers;
        private SpriteFont TouchFont;
        private Vector2 coordinates = new Vector2(10.0f, 0.0f);
        private Boolean newDrag = true;
        private Texture2D background;
        private Texture2D boardBackground;
        private Texture2D boardActiveBackground;
        private Texture2D stackBackgroundShow;
        private Texture2D stackBackgroundHidden;
        private Texture2D passButtonenabled, passButtonClickable, passButtonClicked;

        private Object gestureOrigin;
        private Object gestureTarget;
        private GestureType gestureState;
        private GestureSample gesture;
        private Vector2 huidigGesture;
        private Vector2 huidigGesture2; // used for pinch
        private Vector2 startGesture;
        private Vector2 startGesture2; // used for pinch
        private Vector2 stackStartGesture;
        private Boolean newGesture = true;
        private Triominoe inHand;
        private Texture2D twoplayerButtons, oneplayerButton;
        private Rectangle twoPlayerCoor, onePlayerCoor;
        private bool showPopUpScreenChangeTurn = false;
        private bool showPopUpScreenWin = false;
        private Rectangle popUpScreenCoor;
        private Texture2D popUpScreen;
        private StartScreen startScreen;
        private bool multiPlayer;

        private Player winner, loser;

        private enum GAMESTATE
        {
            STARTSCREEN,    // startscreen, startgame
            INITIALISE,     // create game components, stack, slates and table
            SHUFFLE,        // Shuffle the stack and give each player 9 Triominoes.
            OFFER,          // Each player offers stones to determine who begins the game.
            BEGIN,          // Play the offered stone of the player who offered the highest stone.
            PLAY,           // Play a normal turn.
            END,            // End the round and give the winner bonus points.
            DONE            // all done. Owari da!
        };

        private GAMESTATE gameState = GAMESTATE.STARTSCREEN;
        
        private int passes = 0; // the number of consecutive turns in which no Triominoe was played

        private int counter = 500;

        Boolean checkMove = false;
        Vector2 tableSpeed = new Vector2(0);

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            // Frame rate is 30 fps by default for Windows Phone.
            TargetElapsedTime = TimeSpan.FromTicks(333333);

            // Extend battery life under lock.
            InactiveSleepTime = TimeSpan.FromSeconds(1);
            TouchPanel.EnabledGestures = GestureType.Tap | GestureType.FreeDrag | GestureType.DragComplete | GestureType.Pinch | GestureType.PinchComplete | GestureType.None | GestureType.DoubleTap;
            
            //landscape view
            graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft;
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            basicEffect = new BasicEffect(graphics.GraphicsDevice);
            basicEffect.VertexColorEnabled = true;
            basicEffect.Projection = Matrix.CreateOrthographicOffCenter
               (0, graphics.GraphicsDevice.Viewport.Width,     // left, right
                graphics.GraphicsDevice.Viewport.Height, 0,    // bottom, top
                0, 1);                                         // near, far plane

            containers = new TriominoeContainer[3];
            slateContainers = new SlateContainer[2];

            players = new Player[2];       

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            tableTexture = Content.Load<Texture2D>("TriominoesTable");
            background = Content.Load<Texture2D>("images/background_trio_variant2");
            boardBackground = Content.Load<Texture2D>("images/slate_board_normal");
            boardActiveBackground = Content.Load<Texture2D>("images/slate_board_your_turn");
            stackBackgroundShow = Content.Load<Texture2D>("images/stack_background_show");
            stackBackgroundHidden = Content.Load<Texture2D>("images/stack_background_hidden");

            triominoeFont = Content.Load<SpriteFont>("Triominoe");
            TouchFont = Content.Load<SpriteFont>("Triominoe");

            passButtonenabled = Content.Load<Texture2D>("images/pass_button_enabled");
            passButtonClickable = Content.Load<Texture2D>("images/pass_button_clickable");
            passButtonClicked = Content.Load<Texture2D>("images/pass_button_clicked");

            oneplayerButton = Content.Load<Texture2D>("images/1player_button");
            onePlayerCoor = new Rectangle((graphics.GraphicsDevice.Viewport.Width / 2) - (oneplayerButton.Width / 2), (graphics.GraphicsDevice.Viewport.Height / 2) - oneplayerButton.Height, oneplayerButton.Width, oneplayerButton.Height);
           
            twoplayerButtons = Content.Load<Texture2D>("images/2players_button");
            twoPlayerCoor = new Rectangle((graphics.GraphicsDevice.Viewport.Width / 2) - (twoplayerButtons.Width / 2), (graphics.GraphicsDevice.Viewport.Height / 2), twoplayerButtons.Width, twoplayerButtons.Height);
            
            
            popUpScreen = Content.Load<Texture2D>("images/popup_screen");
            popUpScreenCoor = new Rectangle((graphics.GraphicsDevice.Viewport.Width / 2) - (popUpScreen.Width / 2), (graphics.GraphicsDevice.Viewport.Height / 2) - (popUpScreen.Height / 4), popUpScreen.Width, popUpScreen.Height/2);

            startScreen = new StartScreen(new Rectangle(GraphicsDevice.Viewport.X, GraphicsDevice.Viewport.Y, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height), TRIO_MAX_VAL, triominoeFont);
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        /// 

       
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                if (gameState == GAMESTATE.STARTSCREEN)
                    this.Exit();
                else
                    gameState = GAMESTATE.STARTSCREEN;

            newGesture = true;

            switch (gameState)
            {
                case GAMESTATE.STARTSCREEN:
                    //reset all variable
                    X_NEXT_TRIOMINOE_IN_SLATE = 250;

                    startScreen.Update(gameTime);    
                    break;
                case GAMESTATE.INITIALISE:
                    // make new offer pad POSTPONED

                    table = new GameTable(tableTexture, graphics.GraphicsDevice, triominoeFont, 0.8f);

                    PassButton btn = new PassButton(passButtonClicked, passButtonClickable, passButtonenabled, new Rectangle());

                    slateContainers[0] = new SlateContainer(triominoeFont, TRIO_MAX_VAL, 
                        new Rectangle(50, 10, graphics.GraphicsDevice.Viewport.Width-100, 100), 
                        new Rectangle(200, 10, graphics.GraphicsDevice.Viewport.Width-250, 100),
                        boardBackground, boardActiveBackground, btn);

                    btn = new PassButton(passButtonClicked, passButtonClickable, passButtonenabled, new Rectangle());

                    slateContainers[1] = new SlateContainer(triominoeFont, TRIO_MAX_VAL,
                        new Rectangle(50, graphics.GraphicsDevice.Viewport.Height - 110, graphics.GraphicsDevice.Viewport.Width - 100, 100),
                        new Rectangle(200, graphics.GraphicsDevice.Viewport.Height - 110, graphics.GraphicsDevice.Viewport.Width - 250, 100),
                        boardBackground, boardActiveBackground, btn);

                    stackContainer = new StackContainer(
                        new Rectangle(0, (graphics.GraphicsDevice.Viewport.Height / 2) - 150, 300, 300), 
                        new Rectangle(0, (graphics.GraphicsDevice.Viewport.Height / 2) - 150, 100, 300),
                        new Rectangle(0, (graphics.GraphicsDevice.Viewport.Height / 2) - 150, 250, 300),
                        stackBackgroundShow, stackBackgroundHidden, TRIO_MAX_VAL, triominoeFont, graphics);

                    if (multiPlayer)
                    {
                        players[0] = new Player(1, "Player1");
                        players[1] = new Player(2, "Player2");
                    }
                    else
                    {
                        players[0] = new Player(1, "Trio Bot");
                        players[1] = new Player(2, "Player");
                    }
                    players[0].setSlate(slateContainers[0]);
                    players[1].setSlate(slateContainers[1]);

                    gameState = GAMESTATE.SHUFFLE;
                    break;
                case GAMESTATE.SHUFFLE:
                    counter -= gameTime.ElapsedGameTime.Milliseconds;
                    if (counter < 0)
                    {
                        if (slateContainers[0].container.numberOfTriominoes() == NUM_START_TRIOS)
                        {
                            gameState = GAMESTATE.OFFER;
                        }
                        else
                        {
                            stackContainer.container.moveTriominoeToContainer(
                                stackContainer.container.getTriominoe(), slateContainers[0].container, X_NEXT_TRIOMINOE_IN_SLATE);
                            stackContainer.container.moveTriominoeToContainer(
                                stackContainer.container.getTriominoe(), slateContainers[1].container, X_NEXT_TRIOMINOE_IN_SLATE);

                            counter = TIME_DIVIDE;
                            X_NEXT_TRIOMINOE_IN_SLATE += 50;
                        }
                    }
                    break;
                case GAMESTATE.OFFER:
                    {
                        Triominoe highest1 = players[0].getSlate().container.getHighestTriominoe();
                        Triominoe highest2 = players[1].getSlate().container.getHighestTriominoe();

                        Triominoe highest;
                        Player beginner;

                        if (highest1.getValue() >= highest2.getValue())
                        {
                            highest = highest1;
                            beginner = players[0];
                            playingPlayer = players[0];
                        }
                        else
                        {
                            highest = highest2;
                            beginner = players[1];
                            playingPlayer = players[1];
                        }

                        bool worked = table.addTriominoeToFace(table.getFirstFace(), highest, triominoeFont);
                        beginner.getSlate().container.removeTriominoe(highest);
                        beginner.addScore(10 + highest.getValue());

                        changeTurn();

                        gameState = GAMESTATE.PLAY;
                    }
                    break;
                case GAMESTATE.PLAY:
                    if(stackContainer.container.numberOfTriominoes() == 0)
                        playingPlayer.getSlate().getPassBtn().isEnabled(true);
                    
                    Vector2 center = new Vector2(GraphicsDevice.Viewport.X / 2, GraphicsDevice.Viewport.Y / 2);
                    Vector2 tableCenter = table.getCenterFace();
                    center = center - tableCenter;

                    if ((center * center).Length() < 200000)
                        checkMove = false;

                    if (checkMove )
                    table.move(tableSpeed * 6);

                    if (stackContainer.container.numberOfTriominoes() == 0 && passes == 2)
                    {
                        gameState = GAMESTATE.END;
                    }

                    if (slateContainers[0].container.numberOfTriominoes() == 0 ||
                        slateContainers[1].container.numberOfTriominoes() == 0)
                    {
                        gameState = GAMESTATE.END;
                    }

                    //if (slateContainers[0].container.numberOfTriominoes() == 0 ||
                    //    slateContainers[1].container.numberOfTriominoes() == 0 && multiPlayer == true)
                    //{
                    //   // changeTurn();
                    //    gameState = GAMESTATE.END;
                    //}

                    break;
                case GAMESTATE.END:
                    

                    if (players[0].getSlate().container.getValue() < players[1].getSlate().container.getValue())
                    {
                            winner = players[0];
                            loser = players[1];
                    }
                    else if (players[0].getSlate().container.getValue() > players[1].getSlate().container.getValue())
                    {
                            winner = players[1];
                            loser = players[0];
                    }
                    else
                    {
                        winner = players[0] != playingPlayer ? players[0] : players[1];
                        loser = players[1] != playingPlayer ? players[1] : players[0];
                    }

                    if (winner.getSlate().container.numberOfTriominoes() == 0)
                        winner.addScore(25);


                    winner.addScore(- winner.getSlate().container.getValue());
                    winner.addScore(loser.getSlate().container.getValue());

                    gameState = GAMESTATE.DONE;
                    break;
                case GAMESTATE.DONE:
                    showPopUpScreenChangeTurn = false;
                    showPopUpScreenWin = true;
                    break;
            }

            while (TouchPanel.IsGestureAvailable)
            {
                gesture = TouchPanel.ReadGesture();
                if(newGesture)
                    gestureState = gesture.GestureType;
                if (gameState == GAMESTATE.STARTSCREEN)
                {
                    switch (gestureState)
                    {
                        case GestureType.Tap:
                            newGesture = false;
                            if (gesture.Position.X > twoPlayerCoor.X && gesture.Position.X < (twoplayerButtons.Width + twoPlayerCoor.X) &&
                                    gesture.Position.Y > twoPlayerCoor.Y && gesture.Position.Y < (twoplayerButtons.Height + twoPlayerCoor.Y))
                            {
                                gameState = GAMESTATE.INITIALISE;
                                newGesture = false;
                                multiPlayer = true;
                            }
                            else if (gesture.Position.X > onePlayerCoor.X && gesture.Position.X < (oneplayerButton.Width + onePlayerCoor.X) &&
                                    gesture.Position.Y > onePlayerCoor.Y && gesture.Position.Y < (oneplayerButton.Height + onePlayerCoor.Y))
                            {
                                gameState = GAMESTATE.INITIALISE;
                                newGesture = false;
                                multiPlayer = false;
                            }
                            break;
                    }
                }
                else
                {
                switch (gestureState)
                {
                    case GestureType.Tap:
                        newGesture = false;

                        gestureOrigin = getGestureOrigin(gesture.Position);
                        //change turn popup
                        if (showPopUpScreenChangeTurn)
                        {
                            if (gesture.Position.X > popUpScreenCoor.X && gesture.Position.X < (popUpScreen.Width + popUpScreenCoor.X) &&
                                    gesture.Position.Y > popUpScreenCoor.Y && gesture.Position.Y < (popUpScreen.Height + popUpScreenCoor.Y))
                            {
                                showPopUpScreenChangeTurn = false;
                                newGesture = false;
                                playingPlayer.getSlate().flipAllTrio(true);
                            }
                        }
                        //game won popup
                        if (showPopUpScreenWin)
                        {
                            if (gesture.Position.X > popUpScreenCoor.X && gesture.Position.X < (popUpScreen.Width + popUpScreenCoor.X) &&
                                    gesture.Position.Y > popUpScreenCoor.Y && gesture.Position.Y < (popUpScreen.Height + popUpScreenCoor.Y))
                            {
                                showPopUpScreenWin = false;
                                newGesture = false;
                                gameState = GAMESTATE.STARTSCREEN;
                            }
                        }
                        if (playingPlayer != null)
                        {
                            if (gestureOrigin == playingPlayer.getSlate())
                                inHand = ((SlateContainer)playingPlayer.getSlate()).container.
                                    getTriominoe(gesture.Position.X, gesture.Position.Y);

                            if (gestureOrigin == playingPlayer.getSlate().getPassBtn())
                            {
                                playingPlayer.getSlate().getPassBtn().Click();
                                playingPlayer.addScore(-10);
                                passes++;
                                changeTurn();
                            }
                        }

                        //inHand = getTriominoe(gesture.Position.X, gesture.Position.Y);
                        if(inHand != null)
                            inHand.rotate();
                        inHand = null;
                        break;
                    case GestureType.FreeDrag:
                        newGesture = false;
                        if (newDrag)
                        {
                            gestureOrigin = getGestureOrigin(gesture.Position);
                            startGesture = gesture.Position;

                            stackStartGesture = startGesture;

                            if (gestureOrigin == stackContainer ||
                                playingPlayer != null && gestureOrigin == playingPlayer.getSlate())
                            {
                                inHand = getTriominoe(startGesture.X, startGesture.Y);
                            }
                            
                            newDrag = false;
                        }

                        huidigGesture = gesture.Position;
                        
                        if (gestureOrigin.GetType() == typeof(GameTable))
                        {
                            table.move(huidigGesture - startGesture);
                        }

                        if(inHand != null)
                            inHand.move(huidigGesture - startGesture);
                        startGesture = huidigGesture;
                        
                        break;
                    case GestureType.DragComplete:
                        gestureTarget = getGestureOrigin(huidigGesture);
                        
                        if (gestureOrigin.GetType() == typeof(StackContainer))
                        {
                            if (gestureTarget.GetType() == typeof(GameTable))
                            {
                                if (stackContainer.isHidden())
                                    stackContainer.showStack();
                            }
                            if (gestureTarget.GetType() == typeof(SlateContainer))
                            {
                                if (stackContainer.isHidden())
                                    stackContainer.showStack();

                                if (inHand != null)
                                {
                                    SlateContainer cont = playingPlayer.getSlate();

                                    if (gestureTarget == cont)
                                    {
                                        if (playingPlayer.getCountBoughtTriominoe() < 3)
                                        {
                                            //TODO: check of stack leeg is. 
                                            stackContainer.container.moveTriominoeToContainer(inHand, ((SlateContainer)gestureTarget).container);
                                            playingPlayer.playerBuyTriominoe();
                                            playingPlayer.addScore(-5);
                                        }
                                        if (playingPlayer.getCountBoughtTriominoe() == 3)
                                            playingPlayer.getSlate().getPassBtn().isEnabled(true);
                                    }
                                }
                            }
                            if (gestureTarget.GetType() == typeof(StackContainer))
                            {
                                if (stackStartGesture.X < huidigGesture.X && stackContainer.isHidden())
                                    stackContainer.showStack();
                                if (stackStartGesture.X > huidigGesture.X && !stackContainer.isHidden())
                                    stackContainer.hiddenStack();
                            }
                        }
                        if (gestureOrigin.GetType() == typeof(SlateContainer))
                        {
                            if (gestureOrigin == playingPlayer.getSlate() && gestureTarget.GetType() == typeof(GameTable))
                            {
                                if (inHand != null)
                                {
                                    GridFace f = table.getFace(inHand.getLocation().X, inHand.getLocation().Y);

                                    bool match = false;

                                    if(f != null)
                                        match = table.addTriominoeToFace(f, inHand, triominoeFont);

                                    if (match)
                                    {
                                        playingPlayer.getSlate().container.removeTriominoe(inHand);
                                        playingPlayer.addScore(inHand.getValue());
                                        passes = 0;
                                        changeTurn();
                                    }
                                }
                            }
                        }
                        
                        newGesture = false;
                        newDrag = true;
                        inHand = null;
                        break;
                    case GestureType.Pinch:
                        // zoom dat table
                        break;
                    case GestureType.PinchComplete:
                        break;
                    case GestureType.DoubleTap:
                        
                        if (gameState == GAMESTATE.PLAY && gestureOrigin.GetType() == typeof(GameTable))
                        {
                            checkMove = true;
                        }

                        if (checkMove == true)
                        {
                            Vector2 triominoePosition = table.getCenterFace();
                            Vector2 screenMiddle = new Vector2(graphics.GraphicsDevice.Viewport.Width / 2, graphics.GraphicsDevice.Viewport.Height / 2);

                            tableSpeed = (screenMiddle - triominoePosition);
                            tableSpeed.Normalize();
                        }
                        break;
                    case GestureType.Flick:
                        //change turn popup
                        if (showPopUpScreenChangeTurn)
                        {
                                showPopUpScreenChangeTurn = false;
                                newGesture = false;
                                playingPlayer.getSlate().flipAllTrio(true);
                        }
                        //game won popup
                        if (showPopUpScreenWin)
                        {
                            if (gesture.Position.X > popUpScreenCoor.X && gesture.Position.X < (popUpScreen.Width + popUpScreenCoor.X) &&
                                    gesture.Position.Y > popUpScreenCoor.Y && gesture.Position.Y < (popUpScreen.Height + popUpScreenCoor.Y))
                            {
                                showPopUpScreenWin = false;
                                newGesture = false;
                                gameState = GAMESTATE.STARTSCREEN;
                            }
                        }
                        break;
                    }
                }
            }

            if (gameState != GAMESTATE.STARTSCREEN && gameState != GAMESTATE.INITIALISE)
            {
                stackContainer.Update(gameTime, inHand);
                foreach (SlateContainer sl in slateContainers)
                    sl.Update(gameTime, inHand);

            }


            
            base.Update(gameTime);
        }

        public Object getGestureOrigin(Vector2 position)
        {
            if (playingPlayer != null && playingPlayer.getSlate().getPassBtn().isEnabled())
            {
                if (playingPlayer.getSlate().getPassBtn().inBounds(position))
                    return playingPlayer.getSlate().getPassBtn();
            }

            if (stackContainer.checkInContainer(position))
                return stackContainer;
            if (slateContainers[0].checkInContainer(position))
                return slateContainers[0];
            if (slateContainers[1].checkInContainer(position))
                return slateContainers[1];
            return table;
        }

        public Player changeTurn()
        {
            players[0].setTurn(false);
            players[1].setTurn(false);

            if (playingPlayer != players[0])
                playingPlayer = players[0];
            else
                playingPlayer = players[1];

            playingPlayer.setTurn(true);

            if (multiPlayer)
            {
                foreach (Player p in players)
                    p.getSlate().flipAllTrio(false);
                showPopUpScreenChangeTurn = true;
                
            }
            else
            {
                players[0].getSlate().flipAllTrio(false);
                players[1].getSlate().flipAllTrio(true);
                //its phones turn
                if (playingPlayer.getNumber() == 1 && players[1].getSlate().container.numberOfTriominoes() > 0)
                    doTurnTrio();
            }

            return playingPlayer;
        }

        public void doTurnTrio()
        {
            bool canPlay = false;
            Triominoe[] trios = playingPlayer.getSlate().container.getTriominoes();
            List<GridFace> faces = table.getFaces();

            Triominoe goodTrio = null;
            GridFace goodFace = null;
            
            foreach (Triominoe t in trios)
            {
                //use rotate
                if (t != null)
                {
                    for (int i = 0; i < 360; i += 60)
                    {
                        t.setRotation(i);
                        for (int j = 0; j < faces.Count; j++)
                        {
                            //is plek leeg en staat trio in goede positie
                            if (faces[j] != null && !faces[j].isFilled() )
                            {
                                if (table.addTriominoeToFace(faces[j], t, triominoeFont))
                                {
                                    canPlay = true;
                                    goodFace = faces[j];
                                    goodTrio = t;
                                }
                                if(canPlay)
                                    break;
                            }
                        }
                        if(canPlay)
                            break;
                    }
                }
                if (canPlay)
                    break;
            }
            //do turn
            if (canPlay)
            {
                playingPlayer.getSlate().container.removeTriominoe(goodTrio);
                playingPlayer.addScore(goodTrio.getValue());
                passes = 0;
                if(playingPlayer.getSlate().container.numberOfTriominoes() > 0)
                    changeTurn();
            }
            else if (playingPlayer.getCountBoughtTriominoe() < 3 && stackContainer.container.numberOfTriominoes() != 0)
            {
                stackContainer.container.moveTriominoeToContainer(stackContainer.container.getTriominoe(), playingPlayer.getSlate().container);

                playingPlayer.playerBuyTriominoe();
                playingPlayer.addScore(-5);
                doTurnTrio();
            }
            else
            {
                passes++;
                playingPlayer.pass();
                if (playingPlayer.getSlate().container.numberOfTriominoes() > 0)
                    changeTurn();
            }
        }

        public Triominoe getTriominoe(float x, float y)
        {
            if (inHand != null)
                return inHand;

            Triominoe t = null;

            if (!stackContainer.isHidden())
            {
                TriominoeContainer tc = stackContainer.container;
                if (tc != null)
                    t = tc.getTriominoe(x, y);
                if (t != null) return t;
            }

            //TODO, coordienaten kloppen niet helemaal
            foreach (SlateContainer sl in slateContainers)
            {
                TriominoeContainer tc1 = sl.container;
                if (tc1 != null)
                    t =  tc1.getTriominoe(x, y);
                if(t != null) return t;
            }
            
            return t;
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            
            //background tafel
            spriteBatch.Begin();
                spriteBatch.Draw(background, new Rectangle(0, 0, graphics.GraphicsDevice.Viewport.Width, graphics.GraphicsDevice.Viewport.Height), Color.White);
            spriteBatch.End();

            if (gameState == GAMESTATE.STARTSCREEN)
            {
       
                startScreen.draw(GraphicsDevice, spriteBatch, triominoeFont, basicEffect);

                spriteBatch.Begin(); 
                spriteBatch.Draw(oneplayerButton, onePlayerCoor, Color.White);
                spriteBatch.Draw(twoplayerButtons, twoPlayerCoor, Color.White);
                spriteBatch.End();
            }
            else
            {
                //stenen op tafel
                if (table != null)
                    table.Draw(GraphicsDevice, spriteBatch, basicEffect, triominoeFont);

                //trio containers
                //if(slateContainers != null)
                //    foreach (SlateContainer sl in slateContainers)
                //        if(sl != null)
                //            sl.Draw(GraphicsDevice, spriteBatch, triominoeFont, basicEffect);

                if (players != null)
                    foreach (Player p in players)
                        if (p != null && p.getSlate() != null)
                            p.Draw(GraphicsDevice, spriteBatch, triominoeFont, basicEffect);

                if (stackContainer != null)
                    stackContainer.Draw(GraphicsDevice, spriteBatch, triominoeFont, basicEffect);

                if (showPopUpScreenChangeTurn)
                {
                    spriteBatch.Begin();
                    spriteBatch.Draw(popUpScreen, popUpScreenCoor, Color.White);
                    popUpText = new AnchoredText(triominoeFont, playingPlayer.getName() + "'s turn!!", new Vector2(GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2),
                                0f, TextAnchor.MiddleCenter, 2f);
                    popUpText.Draw(spriteBatch);
                    spriteBatch.End();
                }
                if (showPopUpScreenWin)
                {
                    spriteBatch.Begin();
                    spriteBatch.Draw(popUpScreen, popUpScreenCoor, Color.White);
                    popUpText = new AnchoredText(triominoeFont,  winner.getName() + " WINS!!!\nScore: " + winner.getScore(), new Vector2(GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2),
                                0f, TextAnchor.MiddleCenter, 1f);
                    popUpText.Draw(spriteBatch);
                    spriteBatch.End();
                }
            }
            base.Draw(gameTime);
        }

        private AnchoredText popUpText;
    }
}
